package cn.wsn2018.tools.aop;

import cn.wsn2018.tools.dao.UserDao;
import cn.wsn2018.tools.model.SystemConfig;
import cn.wsn2018.tools.model.User;
import cn.wsn2018.tools.util.StringUtil;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

@Aspect
@Component

/**
 * 做一些处理
 * */
public class WebAspect {

    @Autowired
    private UserDao userDao;

    @Before("execution(public String cn.wsn2018.tools.service.SecUserService.listSecUsers(..))")
    public  void checkLockedState(){
        //检查被锁定的用户是否满足解锁条件
        List<User> users = userDao.listLockedSecuser();
        for(User u:users){
            //获取系统配置
            SystemConfig systemConfig = SystemConfig.getInstance();
            //设定的锁定时间，单位:分钟
            String lockedTime = systemConfig.getLockedTime();

            String lockedDateTime = u.getLockedDateTime();
            DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss");
            //被锁定时间
            LocalDateTime lastLockedDateTime =null;
            if(StringUtil.isEmptyString(lockedDateTime)){
                //锁定时间为空 异常
                continue;
            }else{
                //用户被锁定时间
                lastLockedDateTime = LocalDateTime.parse(lockedDateTime, fmt);
                //现在的时间
                LocalDateTime now = LocalDateTime.now();
                if(now.isAfter(lastLockedDateTime.plusMinutes(Integer.parseInt(lockedTime)))){
                    //解锁用户
                    userDao.unlockSecUserById(u.getId());
                }
            }
        }
    }


}
